package com.newegg.datafeed.adserving.service;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.newegg.datafeed.adserving.domain.Company;
import com.newegg.datafeed.adserving.mapper.CompanyMapper;
import com.newegg.datafeed.adserving.mapper.UserMapper;
import com.newegg.datafeed.adserving.response.Page;

@Service
@Transactional
public class CompanyService {
	
	@Autowired
	CompanyMapper companyMapper;
	
	@Autowired
	UserMapper userMapper;

	public Boolean checkExist(String user) {
		List<String> users = companyMapper.checkName(user);
		if(users == null || users.isEmpty()){ return false; }
		return true;
	}

	public Company save(Company company) {
		if(checkExist(company.getAccount())){
			throw new RuntimeException("this account has exist");
		}
		company.setVerify(false);
		company.setUpdateDate(new Date());
		company.setCreateDate(new Date());
		companyMapper.insert(company);
		return company;
	}

	public Page<Company> page(int pageIndex, int pageSize) {
		if(pageIndex < 1){ pageIndex = 1;}
		Page<Company> page = new Page<Company>();
		page.setTotal(companyMapper.count());
		page.setDatas(companyMapper.page((pageIndex - 1) * pageSize, pageSize));
		page.setPageIndex(pageIndex);
		page.setPageSize(pageSize);
		page.getDatas().forEach(c->{ c.security(); });
		return page;
	}

	public void verify(int id, String user) {
		Company company = companyMapper.get(id);
		Assert.notNull(company, "this item has not exist");
		company.setVerify(true);
		company.setVerifyBy(user);
		companyMapper.update(company);
	}

	public Company update(Company company) {
		Company old = companyMapper.get(company.getId());
		Assert.notNull(old, "this item has not exist");
		company.setVerify(old.getVerify());
		company.setVerifyBy(old.getVerifyBy());
		if(company.getDisable() == null){
			company.setDisable(old.getDisable());
		}
		company.setUpdateDate(new Date());
		if(StringUtils.isEmpty(company.getPassword())){
			company.setPassword(old.getPassword());
		}
		companyMapper.update(company);
		company.security();
		return company;
	}

	public void delete(int id) {
		userMapper.deleteByCompany(id);
		companyMapper.delete(id);
	}
}
